package csel.controller.listeners;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashSet;
import java.util.Set;

import csel.controller.bindings.KeyBindings;
import csel.controller.decoders.EventDecoder;
import csel.controller.enums.ActionEnum;
import csel.controller.events.KeyPress;

/**
 * Purpose: This is an event listener for the keyboard
 * 
 * @author Nikolas Wolfe
 */

public class KeyboardListener implements KeyListener
{
	private final Thread decoder;
	private final EventDecoder<KeyPress> eventdecoder;
	private final KeyBindings keyBindings;
	private final Set<ActionEnum> moveSet; 
	
	public KeyboardListener(EventDecoder<KeyPress> ed, KeyBindings keyBindings)
	{
		this.keyBindings = keyBindings;
		this.eventdecoder = ed;
		this.decoder = new Thread(eventdecoder);
		this.moveSet = new HashSet<ActionEnum>();
		moveSet.add(ActionEnum.MOVE_EAST);
		moveSet.add(ActionEnum.MOVE_NORTH);
		moveSet.add(ActionEnum.MOVE_NORTHEAST);
		moveSet.add(ActionEnum.MOVE_NORTHWEST);
		moveSet.add(ActionEnum.MOVE_SOUTH);
		moveSet.add(ActionEnum.MOVE_SOUTHEAST);
		moveSet.add(ActionEnum.MOVE_SOUTHWEST);
		moveSet.add(ActionEnum.MOVE_WEST);
	}
	
	public void startDecoder()
	{
		decoder.start();
	}
	
	public void stopDecoder()
	{
		decoder.interrupt();
	}
	
	public void keyPressed(KeyEvent e)
	{
		KeyPress keyPress = new KeyPress(e, keyBindings);
		try
		{
			if( keyBindings.containsKey(e.getKeyCode()) )
			{
				eventdecoder.registerEvent(keyPress);
			}
		} catch (InterruptedException e1)
		{
			Thread.currentThread().interrupt();
		}
	}

	public void keyReleased(KeyEvent e)
	{
		// This only ever issues a stop command, and only if we're moving
		try
		{
			// do nothing if this is not a move key
			if(moveSet.contains(keyBindings.getEnum(e.getKeyCode())))
			{
				e.setKeyCode(-1);
				KeyPress keyPress = new KeyPress(e, keyBindings);
				eventdecoder.registerEvent(keyPress);
			}
			
		} catch (InterruptedException e1)
		{
			Thread.currentThread().interrupt();
		}
	}

	public void keyTyped(KeyEvent e)
	{
		// DOOOOO NOTHING
		
	}
}